<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Taiwan SDK
 *
 * @author dragon.hu add @2016.4.1
 */
require_once 'BaseChannel.php';

//台湾SDK
class Taiwan implements BaseChannel 
{
	
	function __construct() 
	{
		//echo "construct";
	}

	//put your code here
	function android($data) 
	{
		//$paymentKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0W04VSuAE673xi0p/2Zxy/yHwKJN1WYJKxBYnTDvB0RxvnOfCUsQ3hIY7UDDEwJecH4tygM9qTkiWJvLOTzoVu3TgBqQC8d+oDDj/h3AJId42kB1S6wNjXm9nRvpR6si3MGtBrjI9CfcDEIjDK/FQkg5HUzMZ9dhsXj0EYDV8+j8aDdKshzNRqj377bIMwSfdmSD3kYZlw1ppcNPH+D3T7+gaIgy1qa9ctUSehc4hgAZ5m1nVdcNEoFg9uLu7c4vATmAm36UPR5SciajEa+LnGe0IhsXQwHRsszE921eLcF6OS0XH+Ei9nUQcD3oSJfXK9E05Fq6mHg2V2EAVI4ZZwIDAQAB"; //
		$paymentKey = "pn22xk888marx8rcwez9k6wh2443ys4w";  //是这个key
		$ret = $this->paymentCallBack($paymentKey, ANDROID);
		echo $ret;
	}

	function ios($data) 
	{
		$paymentKey=""; //
		$ret = $this->paymentCallBack($paymentKey, IOS);
		echo $ret;
	}

	function paymentCallBack($paymentKey, $platform)
	{
		$orderLog = new ChargeOrder();
		$orderLog->log("taiwan", $_REQUEST);
		
		require (CONFIGPATH . 'db.php');
		$paydbconn = new Database($config['db']);
		$accountConn = new Database($config['center_db']);
		
		$paytype = $_REQUEST['paytype'];  //（0Android，1IOS，2APK）2表示官网充值
		$gamecode = $_REQUEST['gamecode'];  //游戏代码
		$sid = $_REQUEST['sid'];  //游戏服编号
		$uid = $_REQUEST['uid'];  //游戏账号
		$oid = $_REQUEST['oid'];  //游戏方订单编号
		$cmid = $_REQUEST['cmid'];  //回传平台订单编号
		$pid = $_REQUEST['pid'];  //储值  productid
		$money = $_REQUEST['money'];  //玩家付款金额(单位为新台币)
		$point = $_REQUEST['point'];  //玩家获得的游戏币数
		$time = $_REQUEST['time'];  //时间戳
		$hash = $_REQUEST['hash'];  //
		
		$mysign = md5($gamecode.$sid.$uid.$oid.$cmid.$pid.$money.$point.$time.$paymentKey);
		$return = array();
		if($hash == $mysign)  
		{ //验证通过
			 if($paytype != 2)  //非官网充值
			 {
			 	//进行发货
			 	if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $oid, "taiwan", $platform,$cmid))
			 	{
			 		$return['result'] = '1';
			 		$return['message'] = urlencode("数据库写入失败");
			 		$orderLog->log("taiwan",array("order"=>$oid,"money"=>$money,"serverresult"=>"faild"));
			 	}else
			 	{
			 		//支付成功
			 		$return['result'] = '0';
			 		$return['message'] = urlencode("成功");
			 		$orderLog->log("taiwan",array("order"=>$oid,"money"=>$money,"serverresult"=>"success"));
			 	}
			 }
			 else  //官网充值
			 {
			 	
			 	//uid=ec21d43f623d5594ebf41f0b85faa57f&point=100&sid=0&time=1463733642&gamecode=thxq&hash=6ec4301c94205494ee547e583813d3a0&oid=85CD3E5700196949408_GT2016052010033409&money=50&cmid=GT2016052010033409&pid=apk.thxq.gametaiwan.50
			 	$playerdb = getTmpDbConnect(PLATFORM_ALL, 'all', $sid, DBTYPE_GAMESERVER);
			 	//1.通过pid找到productid
			 	$sql = "SELECT * FROM tt_taiwan_product WHERE product_id = '$pid'";
			 	$one = $paydbconn->one($sql);
			 	$productid = $one['my_product_id'];
			 	//2.通过账号找到账号id
			 	$sql = "SELECT id FROM account WHERE name = '$uid'";
			 	$one = $accountConn->one($sql);
			 	$myaccountId = $one['id'];
			 	//3.通过账号id和serverid找到角色id
			 	$sql = "SELECT id FROM player WHERE accountid = '$myaccountId' AND isdelete = 0";  //有可能删除了角色
			 	$one = $playerdb->one($sql);
			 	$roleid = $one['id'];
			 	
			 	//2.充值流程    台服是一个分区下只有一个角色
			 	$result = $this->insertOrder($paydbconn, $orderLog, $money, $productid, $oid, $sid, $roleid, $myaccountId, 'Webtaiwan', ANDROID);
			 	if ($result)
			 	{
			 		//支付成功
			 		$return['result'] = '0';
			 		$return['message'] = urlencode("成功");
			 		$orderLog->log("taiwan",array("order"=>$oid,"money"=>$money,"serverresult"=>"web pay success"));
			 	}
			 	else
			 	{
			 		$return['result'] = '1';
			 		$return['message'] = urlencode("数据库写入失败");
			 		$orderLog->log("taiwan",array("order"=>$oid,"money"=>$money,"serverresult"=>"web pay faild"));
			 	}
			 }
			 
		} else {
			//"$sig验证失败"
			$return['result'] = '2';
			$return['message'] = urlencode("sign验证失败");
			$orderLog->log("taiwan","  order:$oid  sign error sign:$hash mysign:$mysign");
		}
		$ret = json_encode($return);
		return urldecode($ret);
	}
	
	function insertOrder($paydb, $orderlog, $money, $productid, $orderid, $serverid, $roleid, $accountid, $channelid, $platform, $thirdorderid = '') 
	{
		$nowtime = date ( 'Y-m-d H:i:s', time () );
		$sql = "INSERT INTO {pre}payment(orderid,serverid,roleid,accountid,create_time,status,channel,platform,appid,money,finish_time,product_id) VALUES
		('$orderid','$serverid','$roleid','$accountid','$nowtime','1','$channelid','$platform','0','$money','$nowtime','$productid')";
		$res = $paydb->execute ( $sql );
		if ($res == false) {
			$orderlog->log ( "error", "Taiwan execute sql failed! " . $sql );
			return false;
		}
		
		$serverInfo = $paydb->one ( "SELECT * FROM {pre}areasample WHERE `id`='" . $serverid . "'" );
		$one ['orderid'] = ( string ) $orderid;
		$one ['roleid'] = ( int ) $roleid;
		$one ['channel'] = ( string ) $channelid;
		$one ['money'] = ( string ) $money;
		$one ['platform'] = ( int ) $platform;
		$one ['finish_time'] = ( string ) $nowtime;
		$one ['product_id'] = ( int ) $productid;
		
		// 第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = " . $serverid . " AND roleid='" . $roleid . "'";
		$paydb->query ( $sql );
		$rolepayarr = array ();
		while ( $n = $paydb->get_array () ) {
			$rolepayarr [] = $n;
		}
		for($i = 0; $i < count ( $rolepayarr ); $i ++) {
			if (isset ( $rolepayarr [$i] ['money'] )) {
				$paytimes += 1;
			}
		}
		
		$one ['paytimes'] = $paytimes; // 累计支付次数
		$datas [] = $one;
		$json_str = json_encode ( $datas );
		$json_str = str_replace ( " ", "%20", $json_str );
		
		$strResult = vpost ( $serverInfo ['host'] . "json_str=$json_str&action=45", 10 ); // 请求游戏服务器发放充值
		                                                                              // 推送游戏服务器超时或者失败
		if ($strResult === FALSE || $strResult == "fail") {
			// echo "error:area sending fail ";
			// 写log
			$tmpstr = http_build_query ( $one );
			$orderlog->log ( "error", "Taiwan post error!!!" . $tmpstr );
			return false;
		}
		return true;
	}
		
}